$(document).ready(function () {
    //渲染购物车
    function renderShopCart() {
        //从缓存中获取数据
        let goodsList = JSON.parse(localStorage.getItem("shopCat"));
        //渲染数据
        let shopCartstr = "";
        //遍历数组拼接购物车字符串
        goodsList.forEach((item , index) => {
            let tagInfoStr_first = '';
            let tagInfoStr_second = '';
            item.content.tagInfo.firstActivityTag.forEach(_item => {
                tagInfoStr_first += `<p class="returninfo f-toe">${_item.desc}</p>`;
            })
            item.content.tagInfo.secondActivityTag.forEach(_item => {
                tagInfoStr_second += `
            <span class="tagInfoStr_second">
                <span>${_item.desc}</span>
                <i class="iconfont  icon-sanjiao_up"></i>
            </span>`;
            })
            shopCartstr += `
        <div class="goodsItem">
            <ul class="goodsInfo publicUl">
                <li class="checkBox col1">
                    <input type="checkbox" class="itemCheck" item_index="${index}">
                </li>
                <li class="goodDes col2">
                    <div class="descripts">
                        <a href=""><img src="${item.content.imageUrl}" alt=""></a>
                        <div class="textWrap"> 
                            <p class="goodTile">${item.content.title}</p>
                            ${tagInfoStr_first}
                            <div>
                                <p>
                                    ${tagInfoStr_second}
                                </p>
                            </div>
                        </div>
                    </div>
                </li>
                <li class="goodPrice col3">
                    <div class="newprice ">${item.content.prePrice}</div>
                </li>
                <li class="setGoodNum col4">
                    <span class="setCount">
                        <span class="minus">-</span>
                        <input type="text" max="6" min="1" data-value="2" class="goodNum" id="goodNum" value="${item.cont}">
                        <span class="plus">+</span>
                    </span>
                    <p class="limitmsg">每日限购6件</p>
                </li>
                <li class="totalPriceBox col5">
                    <div class="totalPrice">${item.content.prePrice * item.cont}</div>
                </li>
                <li class="controlBox col6">
                    <span class="del_btn" data_id="${item.Id}">删除</span>
                    <span class="addMyLike">加入收藏</span>
                </li>
            </ul>
            <div class="cartInfo">
                <div class="priceInfo">
                    <span>活动优惠: <span>-$</span><span>0</span></span>
                    <span>商品应付总计: <span>$</span><span>${item.content.prePrice * item.cont}</span></span>
                </div>
            </div>
        </div>
        `;

        });
        //将购物车字符串插入到网页中
        $(".shopCarMidBox").append(shopCartstr);
        //dom操作
        //初始化购物车商品总数
        showAllGoodsNum();
        //点击改变物品数量
        changeGoodsNum();
        //checked
        checked();
        del(goodsList);
    }
    //购物车dom操作函数

    //计算商品总数
    function sumMyGoods(){  
       let goodsArr =  $(".goodNum");
       let goodsNum = 0;
       for(let i = 0 ; i < goodsArr.length ; i++){
         goodsNum += Number(goodsArr.eq(i).val());
       }
       return goodsNum;
    }
    //计算并改变商品总价
    function goodsTotalPrice(ele , num){
        //获取当前商品的单价
        let unitPrice =Number(ele.parents("li.setGoodNum").prev(".goodPrice").find(".newprice").text());           
        //当前商品总价
         let totalPrice = unitPrice*num;
         ele.parents("li.setGoodNum").next(".totalPriceBox").find(".totalPrice").text(totalPrice);
    }
    //显示商品总数函数
    function showAllGoodsNum(){
        $(".shopCaTopBox").find("span").html(sumMyGoods());
    }
    //点击按钮改变商品数量
    function changeGoodsNum(){
        addGoodsNum();
        minusGoodsNum();
    }
    //点击增加物品数量
    function addGoodsNum(){
        $(".plus").on("click",function(){
           let num = Number($(this).prev(".goodNum").val());
           num ++;
           num = num >=6 ? 6 : num;
           $(this).prev(".goodNum").val(num);
           showAllGoodsNum();
           //改变商品总价
           goodsTotalPrice($(this) , num);
           shopCartTotalPrince();
        })
    }
    //点击减少物品数量
    function minusGoodsNum(){
        $(".minus").on("click",function(){
            let num = Number($(this).next(".goodNum").val());
            num --;
            num = num <= 0 ? 1: num;
            $(this).next(".goodNum").val(num);
            showAllGoodsNum();
            //改变商品总价
            goodsTotalPrice($(this) , num);
            shopCartTotalPrince();
         })
    }
    //选中商品函数
    function checked(){
        //商品选中
        $(".itemCheck:checkbox").on("change",function(e){
            console.log(e.target.checked);
            if (!e.target.checked) {
                $(".checkAll:checkbox").prop("checked",false);
            }
           shopCartTotalPrince();
           changeSettlement();
        })
        //全选按钮
        // let select = false;
        $(".checkAll:checkbox").on("click",function(e){ 
            console.log(e.target.checked);

            if(e.target.checked){
                $("input:checkbox").prop("checked",true);
            }
            if(!e.target.checked){
                $("input:checkbox").prop("checked",false);
            }
            shopCartTotalPrince();
            changeSettlement();
        })
    }
    //计算选中商总价并显示
    function shopCartTotalPrince(){
       let goodsCheckedArr = $(".itemCheck:checked");
       let totalGoodsNum = 0 ;
       let totalShopCartPrice = 0 ;
       for(let i = 0 ; i < goodsCheckedArr.length ; i ++){
            totalGoodsNum += Number(goodsCheckedArr.eq(i).parents(".goodsInfo").find(".goodNum").val());
            totalShopCartPrice += Number(goodsCheckedArr.eq(i).parents(".goodsInfo").find(".totalPrice").text())
        }
       $(".ttbar").find(".left-num").text(totalGoodsNum);
       $(".ttbar").find(".checkedPrice").text(totalShopCartPrice);

    }
    //改变有商品选中时,结算按钮颜色
    function changeSettlement(){
        let checked = $(".itemCheck:checked");
        if(checked.length > 0 ){
            $(".ttbar").find("dd").css({"background-color": "#fa1d1d"});
            $(".ttbar").find("dd").find("span").css({"color": "#eceaea"});
        }
        if (checked.length===0) {
            $(".ttbar").find("dd").css({"background-color": "#5a2d2d"});
            $(".ttbar").find("dd").find("span").css({"color": "#757575"});
        } 
    }
    //删除
    function del(data){
        $(".delSlected").on("click",function(){
            delSelect(data);           
        })
        delItem(data);
    }
    //删除选中
    function delSelect(data){
        console.log("aa");
        let checkedarr = $(".itemCheck:checked");
        for (let i = 0; i < checkedarr.length; i++) {
            let del = checkedarr.eq(i).parents(".goodsItem");
            del.remove();
        }
        //判断剩余商品是否为0
        // let residualQuantity = $(".itemCheck:checkbox");
        // console.log(residualQuantity);
        // if(residualQuantity.length===0){
        //     $("input:checkbox").removeAttr("checked","checked")
        // }
        let notcheckedarr = $(".itemCheck:not(:checked)");
        let newData = [];
        for(let i = 0 ; i < notcheckedarr.length ; i++){
            let index = notcheckedarr.eq(i).attr("item_index")
            newData.push(data[index]);
        }
        localStorage.removeItem("shopCat");
        localStorage.setItem("shopCat" ,JSON.stringify(newData));
        showAllGoodsNum();
        shopCartTotalPrince();
        changeSettlement();
        
    }
    //点击按钮删除
    function delItem(data){
        $(".controlBox").find("span.del_btn").on("click",function(){
            let id = $(this).attr("data_id")
            $(this).parents(".goodsItem").remove();

            let index;
            for(let i = 0 ; i < data.length ; i++){
               if( data[i].Id === id){
                    index = i;
                    break;
               }
            }
            data.splice(index , 1)
            localStorage.removeItem("shopCat");
            localStorage.setItem("shopCat" ,JSON.stringify(data));
            showAllGoodsNum();
            shopCartTotalPrince();
            changeSettlement();
        })
    }
    
    
       
        
    
    renderShopCart();
})  